package com.guli.sms.controller;

import com.guli.sms.service.SmsService;
import com.guli.utils.R;
import com.guli.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/2
 */

//@CrossOrigin
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone){

        // 验证redis里面是否有验证码信息
        String code = redisTemplate.opsForValue().get(phone);
        // 存在就携带 code到前端
        if (StringUtils.hasText(code)) return R.ok().data("code",code);

        code = RandomUtil.getFourBitRandom();

        // 阿里云短信服务 用不了
        /*HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = smsService.sendSms(phone,"SMS_180051135",param);*/

        // 放入缓存以便于比较  电话号为key 验证码为value
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

        // 自定义：短信验证码改成手动返回 验证码 到前端
        return R.ok().data("code",code);

    }

}
